package com.lvt.design.pattern.module.auth.auth;

import com.lvt.design.pattern.module.auth.apirequest.ApiRequest;
import com.lvt.design.pattern.module.auth.storage.CredentialStorage;
import com.lvt.design.pattern.module.auth.storage.MySqlCredentialStorage;
import com.lvt.design.pattern.module.auth.token.AuthToken;

/**
 * @author LT
 * @date 2023年02月21日 23:03
 */
public class DefaultApiAuthencatorImpl implements ApiAuthencator {

    private CredentialStorage storage;

    public DefaultApiAuthencatorImpl() {
        this.storage = new MySqlCredentialStorage();
    }

    public DefaultApiAuthencatorImpl(CredentialStorage storage) {
        this.storage = storage;
    }

    @Override
    public void auth(String url) {
        ApiRequest request = ApiRequest.buildFromUrl(url);
        auth(request);
    }

    @Override
    public void auth(ApiRequest apiRequest) {
        String appId = apiRequest.getAppID();
        String token = apiRequest.getToken();
        long timeStamp = apiRequest.getTimeStamp();

        AuthToken clientToken = new AuthToken(token, timeStamp);
        if (clientToken.isExpired()) {
            throw new RuntimeException("Token is expired.");
        }
        String password =  storage.getPasswordByAppId(appId);
        AuthToken serverToken = AuthToken.buildAuthToken(apiRequest, password);
        if (!serverToken.match(clientToken)) {
            throw new RuntimeException("Token verfication failed.");
        }
        System.out.println("token verfication success.");
    }
}
